package com.spring.springserver.exception;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

@Component
@Log4j2
public class MyAuthenticationException implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException {
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        if (ex instanceof InsufficientAuthenticationException){
            writer.print("访问此资源需要身份验证");
        }else {
            writer.print(ex.getMessage());
        }
        writer.close();
        response.flushBuffer();
        log.error(ex.getMessage());
    }
}
